/*
 * 文 件 名 : MusicService.java
 * 版    权 : China Machi.Co.,Ltd.Copyright 2009-2011.All rights reserved
 * 描    述 : <描述>
 * 修 改 人 : lixg
 * 修改时间 : 2012-4-20
 * 跟踪单号 : <跟踪单号>
 * 修改单号 : <修改单号>
 * 修改内容 : <修改内容>
 */
package com.fire8.dolphin.service;

import java.io.Serializable;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.IBinder;

import com.fire8.dolphin.common.Constants;
import com.fire8.dolphin.model.FmEntity;
import com.fire8.dolphin.utils.LogUtil;

/**
 * 音乐播放器
 * <功能详细描述>
 *
 * @author  lixg
 * @version [版本号,2012-4-20]
 * @see     [相关类/方法]
 * @since   [产品/模块]
 */
public class MusicService extends Service implements
        MediaPlayer.OnBufferingUpdateListener,
        MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener,
        MediaPlayer.OnErrorListener
{
    private MediaPlayer mediaPlayer;
    
    private BroadcastReceiver receiver;
    
    private FmEntity fm;
    
    private static int STATUS=Constants.MEDIA_STATUS_STOP;
    
    /**
     * @param intent
     * @return
     */
    @Override
    public IBinder onBind(Intent intent)
    {
        return null;
    }
    
    @Override
    public void onCreate()
    {
        super.onCreate();
        LogUtil.d("on create MusicService ");
    }
    
    private void initPlayer()
    {
        LogUtil.d("initPlayer");
        if (mediaPlayer == null)
        {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(3);
            mediaPlayer.setOnPreparedListener(this);
            mediaPlayer.setOnBufferingUpdateListener(this);
            mediaPlayer.setOnErrorListener(this);
            mediaPlayer.setOnCompletionListener(this);
            mediaPlayer.setVolume(100.0F, 100.0F);
        }
        this.receiver = new BroadcastReceiver()
        {
            @Override
            public void onReceive(Context arg0, Intent intent)
            {
                int commend = intent.getIntExtra("command", 0);
                
                //LogUtil.d("command:"+commend);
                switch (commend)
                {
                    case Constants.MEDIA_INIT:
                        fm = (FmEntity)intent.getSerializableExtra("param");
                        resetPlayer(fm);
                        break;
                    case Constants.MEDIA_START:
                        //接到命令，开始播放音乐
                        mediaPlayer.start();
                        sendMessage(Constants.MEDIA_START, "");
                        break;
                    case Constants.MEDIA_PAUSE:
                        //接到命令，暂停播放音乐
                        mediaPlayer.pause();
                        sendMessage(Constants.MEDIA_PAUSE, "");
                        break;
                    case Constants.MEDIA_STOP:
                        release();
                        break;
                    case Constants.BACK_FM:
                        if(getStatus() != Constants.MEDIA_STATUS_STOP)
                        {
                            fm.setTimeLong(mediaPlayer.getDuration());
                            fm.setCurrTime(mediaPlayer.getCurrentPosition());
                            fm.setStatus(getStatus());
                            sendMessage(Constants.BACK_FM,fm);
                        }
                        break;
                    default:
                        break;
                }
            }
            
        };
        registerReceiver(this.receiver, new IntentFilter(Constants.PLAY_CONTROL));
    }
    
    @Override
    public void onStart(Intent intent, int startId)
    {
        super.onStart(intent, startId);
        initPlayer();
        LogUtil.d("onStart");
    }
    
    public void resetPlayer(FmEntity fme)
    {
        try
        {
            LogUtil.d("initPlayer:"+fme.getUrl());
            mediaPlayer.reset();
            mediaPlayer.setDataSource(fme.getUrl());
            mediaPlayer.prepareAsync();
            
        }
        catch (Exception e)
        {
            LogUtil.e("",e);
        }
        
    }
    
    @Override
    public void onDestroy()
    {
        super.onDestroy();
        release();
        unregisterReceiver(receiver);
        
    }
    
    @Override
    public boolean onError(MediaPlayer mp, int what, int extra)
    {
        LogUtil.e("onError");
        LogUtil.e("what:"+what);
        LogUtil.e("extra:"+extra);
        setState(Constants.MEDIA_STATUS_STOP);
        //updatepb.destroy();
        return false;
    }
    private void sendMessage(int command,String param)
    {
        Intent intent = new Intent(Constants.PLAY_CALLBACK);
        Bundle bundle = new Bundle();
        bundle.putInt("command", command);
        bundle.putString("param", param);
        intent.putExtras(bundle);
        sendBroadcast(intent);
    }
    
    private void sendMessage(int command,FmEntity param)
    {
        Intent intent = new Intent(Constants.PLAY_CALLBACK);
        Bundle bundle = new Bundle();
        bundle.putInt("command", command);
        bundle.putSerializable("param", (Serializable)param);
        intent.putExtras(bundle);
        sendBroadcast(intent);
    }
    
    private void setState(int val)
    {
        this.STATUS = val;
    }
    private int getStatus()
    {
        return this.STATUS;
    }
    

    //private Thread 
    
    @Override
    public void onPrepared(MediaPlayer mp)
    {
        //当播放器初始化完成
        mediaPlayer.start();
        setState(Constants.MEDIA_STATUS_PLAYING);
        sendMessage(Constants.MEDIA_INIT,String.valueOf(mediaPlayer.getDuration()));
        fm.setTimeLong(mediaPlayer.getDuration());
        new Thread()
        {
            
            @Override
            public void run()
            {
                while (getStatus() == Constants.MEDIA_STATUS_PLAYING)
                {
                    try
                    {
                        sendMessage(Constants.MEDIA_STATUS_PLAYING,String.valueOf(mediaPlayer.getCurrentPosition()));
                        sleep(1000);
                    }
                    catch (Exception e)
                    {
                        LogUtil.e("",e);
                    }
                }
            }
        }.start();
        
    }
    
    @Override
    public void onCompletion(MediaPlayer mp)
    {
        //播放完成
        setState(Constants.MEDIA_STATUS_STOP);
        sendMessage(Constants.MEDIA_STATUS_STOP, "");
        LogUtil.d("播放完毕");
    }
    
    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent)
    {
        sendMessage(Constants.MEDIA_BUFFER_UPDATE,String.valueOf(percent));
    }
    
    public void release()
    {
        LogUtil.d("release");
        if (mediaPlayer != null)
        {
            mediaPlayer.setOnPreparedListener(null);
            try
            {
                mediaPlayer.stop();
                mediaPlayer.release();
                //setState(MEDIA_NONE);
                mediaPlayer = null;
                setState(Constants.MEDIA_STATUS_STOP);
                LogUtil.d("mediaPlayer.stop()");
            }
            catch (Exception e)
            {
                LogUtil.e("",e);
            }
        }
    }
}
